function res=getHttpTSdata(url)
% result = getHttpTSdata(url)
% gets TS structure from a url
% example: 
%   res = getHttpTSdata('http://ichart.finance.yahoo.com/table.csv?s=SPY');
%

delim = ',';

%----------------------------------------
% read content of url data
%----------------------------------------
data = urlread(url);
%data=java.lang.String(data);
lines=strsplit(data,'\n');
while ~length(lines{end})
  lines = lines(1:end-1);
end

headings=deblank(strsplit(char(lines(1)),delim));
res.header = headings(2:end);
ncol = length(headings)-1;
nrow = length(lines)-1;
res.dates=zeros(nrow,1)*NaN;
res.data=zeros(nrow,ncol)*NaN;
firstdate = deblank(strtok(char(lines(2)), ','));
if isnan(str2double(firstdate))
    % Case 1:  Dates are in a standard format
    dates = cell(nrow, 1);
    for i=2:length(lines)
        fields=deblank(strsplit(char(lines(i)),delim));
        dates(i-1) = fields(1);
        res.data(i-1,1:ncol)=str2double(fields(2:end));
    end
    res.dates = mdt2TSdt(datenum(dates)); 
else
    % Case 2:  Dates are already in the TS format (e.g. YYYYMMDD, YYYYMM)
    for i=2:length(lines)
        fields=str2double(deblank(strsplit(char(lines(i)),delim)));
        res.dates(i-1)=fields(1);
        res.data(i-1,1:ncol)=fields(2:end);
    end
end

return
